package com.cecsmsserve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cecsmsserve.entity.DiningFeedback;
import com.cecsmsserve.entity.User;
import com.cecsmsserve.mapper.DiningFeedbackMapper;
import com.cecsmsserve.mapper.UserMapper;
import com.cecsmsserve.service.DiningFeedbackService;
import com.cecsmsserve.util.result.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Service
public class DiningFeedbackServiceImpl extends ServiceImpl<DiningFeedbackMapper, DiningFeedback> implements DiningFeedbackService {

    @Autowired
    private DiningFeedbackMapper diningFeedbackMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DataSource dataSource; // 注入数据源

    @Override
    public CommonResult insert(DiningFeedback diningFeedback) {
        try {
            diningFeedback.setCreateTime(LocalDateTime.now());
            diningFeedback.setStatus(0);
            int result = diningFeedbackMapper.insert(diningFeedback);
            if (result > 0) {
                return CommonResult.success("提交成功");
            }
            return CommonResult.failed("提交失败");
        } catch (Exception e) {
            return CommonResult.failed("系统异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult reply(DiningFeedback diningFeedback) {
        try {
            diningFeedback.setReplyTime(LocalDateTime.now());
            diningFeedback.setStatus(1);
            int result = diningFeedbackMapper.updateById(diningFeedback);
            if (result > 0) {
                return CommonResult.success("回复成功");
            }
            return CommonResult.failed("回复失败");
        } catch (Exception e) {
            return CommonResult.failed("系统异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult selectByUserId(Integer userId) {
        try {
            QueryWrapper<DiningFeedback> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            return CommonResult.success(diningFeedbackMapper.selectList(wrapper));
        } catch (Exception e) {
            return CommonResult.failed("系统异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult selectByPage(Integer pageNum, Integer pageSize) {
        Page<DiningFeedback> page = new Page<>(pageNum, pageSize);
        QueryWrapper<DiningFeedback> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        return CommonResult.success(this.page(page, wrapper));
    }

    @Override
    public CommonResult selectHandled(Integer pageNum, Integer pageSize) {
        Page<DiningFeedback> page = new Page<>(pageNum, pageSize);
        QueryWrapper<DiningFeedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                   .orderByDesc("create_time");
        
        Page<DiningFeedback> result = this.page(page, queryWrapper);
        
        // 加载所有反馈的用户信息
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            result.getRecords().forEach(feedback -> {
                // 设置用户信息
                if (feedback.getUserId() != null) {
                    feedback.setUser(getUserById(feedback.getUserId()));
                }
                System.out.println("已处理反馈ID: " + feedback.getId() + ", 回复内容: " + feedback.getReply());
            });
        }
        
        return CommonResult.success(result);
    }

    @Override
    public CommonResult selectUnhandled(Integer pageNum, Integer pageSize) {
        Page<DiningFeedback> page = new Page<>(pageNum, pageSize);
        QueryWrapper<DiningFeedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0)
                   .orderByDesc("create_time");
        return CommonResult.success(this.page(page, queryWrapper));
    }

    @Override
    public boolean submitFeedback(DiningFeedback feedback) {
        feedback.setCreateTime(LocalDateTime.now());
        feedback.setStatus(0); // 0表示未处理
        return save(feedback);
    }

    @Override
    public boolean replyFeedback(Integer id, String reply) {
        try {
            System.out.println("收到回复请求：ID=" + id + ", reply='" + reply + "'");
            // 使用专门的方法更新回复内容
            int rows = diningFeedbackMapper.updateReply(id, reply);
            System.out.println("更新结果：影响行数=" + rows);
            
            if (rows > 0) {
                // 验证更新是否成功
                DiningFeedback feedback = getById(id);
                if (feedback != null) {
                    System.out.println("更新后数据：ID=" + feedback.getId() 
                        + ", reply='" + feedback.getReply() + "'"
                        + ", status=" + feedback.getStatus()
                        + ", replyTime=" + feedback.getReplyTime());
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            System.err.println("回复处理异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<DiningFeedback> getUserFeedbacks(Integer userId) {
        LambdaQueryWrapper<DiningFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DiningFeedback::getUserId, userId)
                .orderByDesc(DiningFeedback::getCreateTime);
        return list(wrapper);
    }

    @Override
    public List<DiningFeedback> getUnhandledFeedbacks() {
        LambdaQueryWrapper<DiningFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DiningFeedback::getStatus, 0)
                .orderByDesc(DiningFeedback::getCreateTime);
        
        List<DiningFeedback> list = list(wrapper);
        
        // 加载所有反馈的用户信息
        if (list != null && !list.isEmpty()) {
            list.forEach(feedback -> {
                if (feedback.getUserId() != null) {
                    feedback.setUser(getUserById(feedback.getUserId()));
                }
            });
        }
        
        return list;
    }

    // 根据用户ID获取用户信息的辅助方法
    private User getUserById(Integer userId) {
        try {
            return userMapper.selectById(userId);
        } catch (Exception e) {
            // 如果获取失败，返回一个默认用户对象
            User defaultUser = new User();
            defaultUser.setId(userId);
            defaultUser.setName("用户" + userId);
            return defaultUser;
        }
    }

    // 额外添加一个直接使用JDBC执行SQL的方法
    @Override
    public boolean directReplyFeedback(Integer id, String reply) {
        String sql = "UPDATE dining_feedback SET admin_reply = ?, status = 1, reply_time = NOW() WHERE id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, reply);
            stmt.setInt(2, id);
            
            System.out.println("执行直接SQL: " + sql.replace("?", "'" + reply + "'") + " WHERE id = " + id);
            int rows = stmt.executeUpdate();
            System.out.println("SQL执行结果: " + rows + " 行受影响");
            
            return rows > 0;
        } catch (SQLException e) {
            System.err.println("SQL执行异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
} 